from flask import Blueprint,request,Flask,jsonify
import requests
from service.user_service import UserService
from utils.rpc_utils import RpcUtils

class UserApplication:

    def register_user(password,user_name,user_id):
        print("doing")

        # 外部 API 的 URL
        url = "http://127.0.0.1:8999/register"
        # 请求头，声明发送的数据类型为 JSON
        headers = {
            "Content-Type": "application/json",
        }

        # if res is None:
        #     return False
        # else:
        #     return True
        data = {
            "userId": user_id,
            "deptId": "",
            "userName": user_name,
            "nickName": user_name,
            "password": password,
            "phonenumber": "123",
            "email": "default_email",
            "sex": "1",
            "status": "0",
            "remark": "1",
            "postIds": "",
            "roleIds": ""
        }
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, json=data)
            res_data = response.json()
            if res_data['code'] == 200:
                # 打印响应内容（假设返回的是 JSON 数据）
                print("请求成功！")
                print("响应数据：", res_data['msg'])
                res = UserService.register_user(password,user_name,res_data['user_id'])
                return res_data
            else:
                print(f"请求失败，状态码：{res_data['code']}")
                print("错误信息：", res_data['msg'])
                return res_data
        except requests.exceptions.RequestException as e:
            # 捕获 requests 库抛出的异常（如网络错误）
            print("请求发生错误：", e)
            return False
        
    def update_user_pass(password,user_name,user_id,new_password):

        # 外部 API 的 URL
        url = "http://127.0.0.1:8999/system/syuser_update_user_info"
        # 请求头，声明发送的数据类型为 JSON
        headers = {
            "Content-Type": "application/json",
        }
        # res = UserService.register_user(password,user_name)
        data = {
            "userId": user_id,
            "deptId": "",
            "userName": user_name,
            "nickName": user_name,
            "password": new_password,
            "phonenumber": "1",
            "email": "1231",
            "sex": "1",
            "status": "0",
            "remark": "1",
            "postIds": "",
            "roleIds": ""
        }
        try:
            # 发送 POST 请求
            response = requests.put(url, headers=headers, json=data)
            res_data = response.json()
            print('cao___res_data',res_data)
            if res_data['code'] == 200:
                # 打印响应内容（假设返回的是 JSON 数据）
                print("请求成功！")
                return res_data
            else:
                print(f"请求失败，状态码：{res_data['code']}")
                print("错误信息：", res_data['msg'])
                return res_data
        except requests.exceptions.RequestException as e:
            # 捕获 requests 库抛出的异常（如网络错误）
            print("请求发生错误：", e)
            return res_data
        
    def get_token(user_name,password):
        url = "http://127.0.0.1:8999/login"
        
        headers = {
            "Content-Type": "application/json"
        }

        data={
            "username": user_name,
            "password": password
        }

        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, json=data)
            res_data = response.json()
            print('res_data',res_data)
            if res_data['code'] == 200:
                # 打印响应内容（假设返回的是 JSON 数据）
                print("login响应数据：", res_data['code'])
                return res_data['token']
            else:
                print(f"login请求失败，状态码：{res_data['code']}")
                print("错误信息：", res_data['message'])
                return res_data['token']
        except requests.exceptions.RequestException as e:
            # 捕获 requests 库抛出的异常（如网络错误）
            print("请求发生错误：", e)
            return False
        
    def login(password,user_name):
        try:
            request_body = RpcUtils.rpc_request(user_name,password)
            response = requests.post(request_body[0], headers=request_body[1], json=request_body[2])
            res_data = response.json()
            print('[]cao',res_data)
            print('res_data',res_data)
            if res_data['code'] == 200:
                user = UserService.query_user_by_user_name(user_name)
                print('user',user)
                if user is None:
                    user = UserService.register_user(password,user_name,user_id=res_data['user_id'])
                    user = UserService.query_user_by_user_name(user_name)
                return user
            else:
                return user
        except requests.exceptions.RequestException as e:
            # 捕获 requests 库抛出的异常（如网络错误）
            print("请求发生错误：", e)
            return False
    